package com.example.canteen.service;

import com.example.canteen.converter.PrivateRoomConverter;
import com.example.canteen.dao.PrivateRoom;
import com.example.canteen.dao.PrivateRoomRepository;
import com.example.canteen.dto.PrivateRoomDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Set;
import java.util.stream.Collectors;

@Service
public class PrivateRoomServiceImpl implements PrivateRoomService {
    @Autowired
    PrivateRoomRepository privateRoomRepository;

    @Override
    public Set<PrivateRoomDTO> getAllPrivateRooms() {
        return privateRoomRepository.findAll().stream()
                .map(PrivateRoomConverter::convertPrivateRoom).collect(Collectors.toSet());
    }

    @Override
    public Long addPrivateRoom(PrivateRoomDTO privateRoomDTO) {
        if (privateRoomRepository.findByName(privateRoomDTO.getName()) != null) {
            throw new RuntimeException("already exist");
        }
        return privateRoomRepository.save(PrivateRoomConverter.convertPrivateRoom(privateRoomDTO)).getId();
    }

    @Override
    public PrivateRoomDTO updatePrivateRoom(String oldName, String name) {
        PrivateRoom privateRoomInDB = privateRoomRepository.findByName(oldName);
        if (privateRoomInDB==null){
            return null;
        }
        if (StringUtils.hasLength(name) && !name.equals(oldName)) {
            privateRoomInDB.setName(name);
        }
        return PrivateRoomConverter.convertPrivateRoom(privateRoomRepository.save(privateRoomInDB));
    }
}
